// utils/request.js
import { showLoading, hideLoading, showError } from '@/utils/utils.js'; // 自定义UI工具

// const BASE_URL = 'http://117.72.58.144/prod-api';
const BASE_URL = 'https://saishilong.top/prod-api';
let loadingCount = 0; // 记录当前加载中的请求数量
let isShowingLoginModal = false; // 全局标志位
/**
 * 通用请求方法
 * @param {string} url - 请求路径
 * @param {string} method - 请求方法
 * @param {Object} data - 请求数据
 * @param {Object} options - 额外配置
 * @param {boolean} options.showLoading - 是否显示加载提示
 * @param {string} options.loadingText - 加载提示文本
 * @param {boolean} options.showError - 是否显示错误提示
 * @param {boolean} options.auth - 是否需要认证
 */
function request(url, method = 'GET', data = {}, options = {}) {
  const {
    showLoading: show = true,
    loadingText = '加载中...',
    showError: showErr = true,
    auth = true
  } = options;

  // 显示加载提示
  if (show) {
    if (loadingCount === 0) {
      showLoading(loadingText);
    }
    loadingCount++;
  }

  return new Promise((resolve, reject) => {
    const header = auth ? {
      'Content-Type': 'application/json',
      'Authorization': `${wx.getStorageSync('token') || ''}`
    } : {
      'Content-Type': 'application/json'
    };

    wx.request({
      url: BASE_URL + url,
      method,
      data,
      header,
      success(res) {
        // 处理业务状态码
				uni.hideLoading()
        if (res.data.code === 200) {
          resolve(res.data || res);
        } else if (res.data.code === 401) {
					 if (!isShowingLoginModal) {
						isShowingLoginModal = true; // 标记为已显示
												
						uni.showModal({
							title: '提示',
							content: res.data.msg,
							showCancel: false,
							confirmText: '确认',
							complete: () => {
								uni.navigateTo({
									url: '/pages/login/login'
								})
							}
						})
					}
				} else {
          // 业务错误
          if (showErr) {
            // showError(res.data.msg || '请求失败');
						
						uni.showToast({
							title: res.data.msg || '请求失败',
							icon: 'error',
						})
          }
          reject(new Error(res.data.msg || '接口错误'));
        }
      },
      fail(err) {
        // 网络错误
        if (showErr) {
          showError(`网络错误: ${err.errMsg}`);
        }
        reject(err);
      },
      complete() {
        // 隐藏加载提示
        if (show) {
          loadingCount--;
          if (loadingCount <= 0) {
            loadingCount = 0;
            hideLoading();
          }
        }
      }
    });
  });
}

export default {
  get(url, data = {}, options = {}) {
    return request(url, 'GET', data, options);
  },
  post(url, data = {}, options = {}) {
    return request(url, 'POST', data, options);
  },
  put(url, data = {}, options = {}) {
    return request(url, 'PUT', data, options);
  },
  delete(url, data = {}, options = {}) {
    return request(url, 'DELETE', data, options);
  }
};